import React, { Fragment, useImperativeHandle } from 'react';
import { Form, Input, DatePicker, Radio, Row, Col, Select, ConfigProvider, Divider, Icon } from 'antd';
import moment from 'moment';
import { FormContainer, SelectForm } from '@/components/UserForm';
import CascaderLoad from '@/components/CascaderLoad';
import useUploadAvatar from '@/hooks/useUploadAvatar';
import UploadOss from '@/components/UploadOss';
import { dictionaryList } from '@/services/dictionary';
import styles from '../index.less';

// import { form1VerificationField } from '../jsonForm';

const { Option } = Select;

const Form1 = ({ form, dict, user, avatarFile, dispatch, childRef, entryUser }) => {
    const [fileList, setFileList] = React.useState([]);
    const { getFieldDecorator } = form;
    // const [verificationField] = useState(form1VerificationField); // 需要检测的字段

    const { onFileChange, avatarData, existAvatar, updateAvatar } = useUploadAvatar({
        dispatch,
        user: { ...user, avatarFile: avatarFile.avatarFile }
    });
    const [selectId, setSelectId] = React.useState('');
    const [isChina, setIsChina] = React.useState(false); // 用于户籍类型判断必填
    useImperativeHandle(childRef, () => ({
        updateAvatar
    }));

    // 获得户籍类型remark
    const getSelectId = value => {
        dict.household.map(item => {
            if (value === item.dictValue) {
                setSelectId(item.id);
            }
            return '';
        });
        form.setFieldsValue({
            secondHouseholdType: undefined
        });
    };

    // 获取区号
    const returnDefinedAreaCode = () => (user.companyId === 101 ? '86' : '65');
    const returnAreaCode = areaCode => {
        if (areaCode === '' || areaCode === undefined) {
            return returnDefinedAreaCode();
        }
        return areaCode;
    };

    // 改变籍贯国籍的value值事件
    // 并判断是否为中国
    // 假如发生改变，重置居住地址状态
    const changeNationalArea = e => {
        // 如果籍贯存在中国则作判断
        if (e[0] === '中国') {
            setIsChina(true);
        } else {
            setIsChina(false);
        }
    };
    // 取出必填参数
    const returenRequired = [
        {
            required: true,
            message: '请选择'
        }
    ];

    // 上传按钮样式
    const uploadButton = (
        <div className={styles.uploaderBtn}>
            <Icon type={avatarData.loading ? 'loading' : 'plus'} />
            <div className="ant-upload-text">上传照片</div>
        </div>
    );
    // 获得出生日期
    const autocompleteBirthDay = str => {
        if (str.length > 13) {
            const birthDateStr = str.slice(6, 14);
            const computedBirthDay = moment(birthDateStr, 'YYYYMMDD');
            if (computedBirthDay.format('YYYYMMDD') !== 'Invalid date') {
                form.setFieldsValue({ birthday: computedBirthDay });
            }
        }
    };
    const handleIdCardChange = e => {
        const cardStr = e.target.value;
        const talentNationalArea = form.getFieldValue('nationalArea') || [];
        if (talentNationalArea[0] === '中国') {
            autocompleteBirthDay(cardStr);
        }
    };
    React.useEffect(() => {
        const talentNationalArea = form.getFieldValue('nationalArea') || [];
        const talentIdCard = form.getFieldValue('idCard');
        const talentBirth = form.getFieldValue('birthday');
        if (talentNationalArea[0] === '中国' && talentIdCard && !talentBirth) {
            autocompleteBirthDay(talentIdCard);
        }
    }, [form.getFieldValue('nationalArea')]);

    React.useEffect(() => {
        if (entryUser.firstHouseholdType) {
            getSelectId(entryUser.firstHouseholdType);
        }
        if (entryUser.nationalArea && entryUser.nationalArea.split(',')[0] === '中国') {
            setIsChina(true);
        } else {
            setIsChina(false);
        }
    }, [entryUser, dict]);

    return (
        <Fragment>
            <div className={styles.title} id="form1-1" style={{ marginTop: 0 }}>
                个人信息
            </div>
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                {/* <Form.Item label="邮编">
                        {getFieldDecorator('postCode', {
                            initialValue: '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入邮编'
                                },
                                {
                                    min: 1,
                                    max: 50,
                                    message: '请输入1~50个字符'
                                },
                                {
                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                    message: '此处不能输入空格'
                                }
                            ]
                        })(<Input placeholder="请输入邮编" />)}
                    </Form.Item> */}
                {/* <Form.Item label="工作年限" style={{ marginBottom: 0 }} required>
                        <Row gutter={15}>
                            <Col md={12} xs={24} sm={24}>
                                <Fprm.Item>
                                    {getFieldDecorator('workYear', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择工作年份'
                                            }
                                        ]
                                    })(
                                        <Select placeholder="年份">
                                            {dict.workYear.map(item => (
                                                <Option value={item.dictValue} key={item.dictValue}>
                                                    {item.dictName}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Fprm.Item>
                            </Col>
                            <Col md={12} xs={24} sm={24}>
                                <Form.Item>
                                    {getFieldDecorator('workMonth', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择工作月份'
                                            }
                                        ]
                                    })(
                                        <Select placeholder="月份">
                                            {dict.workMonth.map(item => (
                                                <Option value={item.dictValue} key={item.dictValue}>
                                                    {item.dictName}
                                                </Option>
                                            ))}
                                        </Select>
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form.Item> */}
                <Row gutter={5}>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 12 }}>
                        <Form.Item label="身份证姓名">
                            {getFieldDecorator('employeeName', {
                                initialValue: user.employeeName,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入身份证姓名'
                                    },
                                    {
                                        min: 2,
                                        max: 50,
                                        message: '请输入2~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input placeholder="请输入身份证姓名" />)}
                        </Form.Item>
                        <Form.Item label="证件号码">
                            {getFieldDecorator('idCard', {
                                initialValue: entryUser.idCard,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入证件号码'
                                    },
                                    {
                                        min: 1,
                                        max: 50,
                                        message: '请输入1~50个字符'
                                    },
                                    {
                                        pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                        message: '此处不能输入空格'
                                    }
                                ]
                            })(<Input placeholder="请输入证件号码" onChange={handleIdCardChange} />)}
                        </Form.Item>
                        <Form.Item label="籍贯/国籍">
                            {getFieldDecorator('nationalArea', {
                                initialValue: entryUser.nationalArea && entryUser.nationalArea.split(','),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择籍贯/国籍'
                                    }
                                ]
                            })(
                                <CascaderLoad
                                    cascaderProps={{
                                        placeholder: '请选择籍贯/国籍'
                                    }}
                                    onChange={changeNationalArea}
                                    // asianData={asian}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="居住地址" required style={{ marginBottom: 0 }}>
                            <Form.Item className={styles.nullLabel} style={{ marginBottom: 8 }}>
                                {getFieldDecorator('address', {
                                    initialValue: entryUser.address && entryUser.address.split(','),
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择居住地址'
                                        }
                                    ]
                                })(
                                    <CascaderLoad
                                        cascaderProps={{
                                            placeholder: '请选择居住地址'
                                        }}
                                        // asianData={asian}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item className={styles.nullLabel}>
                                {getFieldDecorator('detailAddress', {
                                    initialValue: entryUser.detailAddress,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入详细居住地址'
                                        },
                                        {
                                            min: 1,
                                            max: 50,
                                            message: '请输入1~50个字符'
                                        },
                                        {
                                            pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                            message: '此处不能输入空格'
                                        }
                                    ]
                                })(<Input.TextArea rows={3} placeholder="请输入详细居住地址" />)}
                            </Form.Item>
                        </Form.Item>
                        <Form.Item label="个人头像">
                            <div className={styles.upload}>
                                <UploadOss
                                    dragAble={false}
                                    uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                                    checkFileSize={3}
                                    checkFileSizeMsg="图片不能大于3M！"
                                    sysCode="OA"
                                    setFileList={(file, uploadResourceResult) => {
                                        setFileList(file);
                                        onFileChange(file, uploadResourceResult);
                                    }}
                                    fileList={fileList}
                                    businessCode="SysAvatar"
                                    categoryCode="avatarFile"
                                    isSingle
                                    checkFileType="JPG,JPEG,BMP,GIF,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,GIF,PNG格式的文件！"
                                >
                                    <div className={styles.uploaderShow}>
                                        {avatarData.url ? (
                                            <img src={avatarData.url ? avatarData.url : existAvatar} alt="avatar" />
                                        ) : (
                                            uploadButton
                                        )}
                                    </div>
                                </UploadOss>
                            </div>
                            <div className={styles.uploadTips}>请上传您的2寸白底近半年内照片</div>
                        </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 12 }}>
                        <Form.Item label="性别">
                            {getFieldDecorator('sex', {
                                initialValue: user.sex,
                                rules: [
                                    {
                                        required: true,
                                        message: '性别不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group>
                                    {dict.sexType.map(item => (
                                        <Radio value={item.dictValue} key={item.dictValue}>
                                            {item.dictName}
                                        </Radio>
                                    ))}
                                </Radio.Group>
                            )}
                        </Form.Item>
                        <Form.Item label="出生日期">
                            {getFieldDecorator('birthday', {
                                initialValue: moment(user.birthday),
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择出生日期'
                                    }
                                ]
                            })(<DatePicker style={{ width: '100%' }} placeholder="请选择出生日期" />)}
                        </Form.Item>

                        {/* 户籍类型 */}
                        {isChina ? (
                            <Form.Item label="户籍类型" required={isChina} style={{ marginBottom: 0 }}>
                                <Row gutter={15}>
                                    <Col md={12} xs={24} sm={24}>
                                        <Form.Item>
                                            {getFieldDecorator('firstHouseholdType', {
                                                initialValue: entryUser.firstHouseholdType || undefined,
                                                rules: isChina ? returenRequired : []
                                            })(
                                                <Select placeholder="请选择" onChange={getSelectId} allowClear>
                                                    {dict.household &&
                                                        dict.household.map(item => (
                                                            <Option value={item.dictValue} key={item.dictValue}>
                                                                {item.dictName}
                                                            </Option>
                                                        ))}
                                                </Select>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col md={12} xs={24} sm={24}>
                                        <Form.Item>
                                            {getFieldDecorator('secondHouseholdType', {
                                                initialValue: entryUser.secondHouseholdType || undefined,
                                                rules: isChina ? returenRequired : []
                                            })(
                                                <SelectForm
                                                    params={{
                                                        parentId: selectId
                                                    }}
                                                    requireParam={['parentId']}
                                                    getData={params =>
                                                        dictionaryList(params).then(res => {
                                                            if (res && res.code === 10000 && res.data) {
                                                                return res.data || [];
                                                            }
                                                            return [];
                                                        })
                                                    }
                                                    fieldsName={{
                                                        selectValue: 'dictValue',
                                                        selectTitle: 'dictName'
                                                    }}
                                                    selectProps={{
                                                        placeholder: '请选择',
                                                        allowClear: true
                                                    }}
                                                />
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form.Item>
                        ) : (
                            ''
                        )}

                        <Form.Item label="最高学历">
                            {getFieldDecorator('highestDegree', {
                                initialValue: user.highestDegree,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择最高学历'
                                    }
                                ]
                            })(
                                <Select placeholder="请选择最高学历">
                                    {dict.agreeType.map(item => (
                                        <Option value={item.dictValue} key={item.dictValue}>
                                            {item.dictName}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Form.Item>
                        {/* 手机号码 区号目前由前端写死 */}
                        <Form.Item label="手机号码">
                            {getFieldDecorator('mobile', {
                                initialValue: user.mobile,
                                rules: [
                                    {
                                        required: true,
                                        validator(rule, value, callback) {
                                            const regex = /^\d{7,11}$/;
                                            if (!value) {
                                                callback('手机号不能为空');
                                            } else if (!regex.test(value)) {
                                                callback('只能输入7-11位数字');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(
                                <Input
                                    placeholder="请填入手机号码"
                                    addonBefore={getFieldDecorator('areaCode', {
                                        initialValue: returnAreaCode(user.areaCode)
                                    })(
                                        <Select placeholder="请选择区号" place style={{ width: 70 }}>
                                            <Option value="86">+86</Option>
                                            <Option value="65">+65</Option>
                                        </Select>
                                    )}
                                />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                <Divider />
                <div className={styles.title} id="form1-2">
                    紧急联系人
                </div>
                <FormContainer>
                    <Form.Item label="姓名">
                        {getFieldDecorator('emergencyContact', {
                            initialValue: entryUser.emergencyContact,
                            rules: [
                                {
                                    required: true,
                                    message: '请输入紧急联系人姓名'
                                },
                                {
                                    min: 2,
                                    max: 50,
                                    message: '请输入2~50个字符'
                                },
                                {
                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                    message: '此处不能输入空格'
                                }
                            ]
                        })(<Input placeholder="请输入紧急联系人姓名" />)}
                    </Form.Item>
                    <Form.Item label="与本人关系">
                        {getFieldDecorator('emergencyRelationship', {
                            initialValue: entryUser.emergencyRelationship,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择与本人关系'
                                }
                            ]
                        })(
                            <Select placeholder="请选择与本人关系">
                                {dict.emergencyRelationship.map(item => (
                                    <Option value={item.dictValue} key={item.dictValue}>
                                        {item.dictName}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="手机号码">
                        {getFieldDecorator('emergencyTelephone', {
                            initialValue: entryUser.emergencyTelephone,
                            rules: [
                                {
                                    required: true,
                                    validator(rule, value, callback) {
                                        const regex = /^\d{7,11}$/;
                                        if (!value) {
                                            callback('手机号不能为空');
                                        } else if (!regex.test(value)) {
                                            callback('只能输入7-11位数字');
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <Input
                                placeholder="请填入手机号码"
                                addonBefore={getFieldDecorator('emergencyAreaCode', {
                                    initialValue:
                                        entryUser.areaCode === '' ? returnDefinedAreaCode() : entryUser.areaCode
                                })(
                                    <Select placeholder="请选择区号" place style={{ width: 70 }}>
                                        <Option value="86">+86</Option>
                                        <Option value="65">+65</Option>
                                    </Select>
                                )}
                            />
                        )}
                    </Form.Item>
                </FormContainer>
                {/* <div className={styles.btnItem}>
                    <Button
                        type="primary"
                        onClick={() => {
                            submit();
                        }}
                    >
                        下一步
                    </Button>
                </div> */}
                <Divider />
            </ConfigProvider>
        </Fragment>
    );
};
export default Form1;
